<template>
  <div class="height-100-per width-100-per bg-color-white padding-10-px">
    <div class="width-100-per">
      <a-tabs @change="callback" type="card">
        <a-tab-pane tab="已审核" key="1"></a-tab-pane>
        <a-tab-pane tab="未审核" key="2"></a-tab-pane>
      </a-tabs>
    </div>
    <div class="width-100-per layout-side margin-bottom-10-px">
      <div>
        <a-button-group v-if="orPass" style="padding: 0 10px 0">
          <a-button style="width: 110px" icon="plus" @click="addUser">人员新增</a-button>
          <a-button v-if="!updateSomeUsers" style="width: 110px" icon="edit" @click="deleteSomeUser">批量删除</a-button>
          <a-button v-if="updateSomeUsers" style="width: 77px" icon="close" @click="deleteSomeUserCancle">取消</a-button>
          <a-button v-if="updateSomeUsers" style="width: 77px" icon="delete" @click="deleteSomeUserOK">删除</a-button>
        </a-button-group>
      </div>
      <div class="layout-side">
        <div class="layout-side">
          <span class="margin-right-5-px">学号</span>
          <a-input class="formInput margin-right-5-px" v-model="selectCodes"></a-input>
        </div>
        <a-button-group>
          <a-button icon="search" @click="selectCode">查询</a-button>
          <a-button icon="reload" @click="removeBack">清空</a-button>
        </a-button-group>
      </div>
    </div>
<!--    :columns="columns"-->
    <a-table
      :locale="{emptyText:'暂无数据'}"
      :rowSelection="rowSelection"
      :rowKey="record => record.key"
      :columns="columns"
      :scroll="{y:contentHeight}"
      :dataSource="userDataTable"
      :pagination="paginationUser"

    >
      <span slot="faceBase64" slot-scope="faceBase64">
        <img :src="faceBase64" width="32px"/>
      </span>
      <span slot="tags" slot-scope="tags">
        <a-tag v-for="tag in tags" color="blue" :key="tag">{{tag}}</a-tag>
      </span>
      <span slot="action" slot-scope="text, record">
        <a @click="onViewClick(record.key)">详情</a>
        <a-divider type="vertical"/>
        <template v-if="orPass">
          <a @click="onEditClick(record.key)">修改</a>
          <a-divider type="vertical"/>
        </template>
        <template v-if="!orPass">
          <a-popconfirm title="确定通过审核吗？" placement="topRight" @confirm="onPassM(record.key)">
            <a @click="">审核</a>
          </a-popconfirm>
          <a-divider type="vertical"/>
        </template>
        <a-popconfirm title="确定删除该人员吗？" placement="topRight" @confirm="onDeleteClick(record.key)">
          <a @click="">删除</a>
        </a-popconfirm>
      </span>
    </a-table>

    <a-modal
      :title="userModalTitle"
      width="600px"
      :visible="modalPersonnel"
      @cancel="cancelPersonnel"
      :footer="footers">
      <template slot="footer">
        <a-button key="back" icon="reload" @click="handleReset">重置</a-button>
        <a-button v-show="addB" key="add" icon="check" type="primary" :loading="loading" @click="addPersonnel">新增提交</a-button>
        <a-button v-show="!addB" key="update" icon="check" type="primary" :loading="loading" @click="updatePersonnel">修改提交</a-button>
      </template>
      <div class="width-100-per layout-side">
        <div class="layout-center-top padding-10-px">
          <div class="layout-side margin-bottom-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>账户名</div>
            <a-input class="formInput" :disabled="disabled" v-model="userData.name"></a-input>
          </div>
          <div class="layout-side margin-bottom-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>编号</div>
            <a-input class="formInput" :disabled="disabled" v-model="userData.code"></a-input>
          </div>
          <div class="layout-side margin-bottom-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>上级建制</div>
            <a-tree-select
              class="formInput"
              :disabled="disabled"
              :value="values"
              :treeData="armyTypesDatas"
              treeDefaultExpandAll
              @select="onSelect"
            />
          </div>
          <div class="layout-side margin-bottom-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>身份类别</div>
            <a-select :disabled="disabled" placeholder="" class="formInput" v-model="userData.userType">
              <a-select-option value="999">请选择</a-select-option>
              <a-select-option v-for="(i,index) in userTypeData" :value="i.key" :key="index">{{i.title}}</a-select-option>
            </a-select>
          </div>
          <div class="layout-side margin-bottom-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>用户类别</div>
            <a-select :disabled="disabled" placeholder="" class="formInput" v-model="userData.armyType">
              <a-select-option value="999">请选择</a-select-option>
              <a-select-option v-for="(i,index) in armyTypeData" :value="i.key" :key="index">{{i.title}}</a-select-option>
            </a-select>
          </div>
          <div class="layout-side margin-bottom-10-px">
            <div class="formSpan">联系方式</div>
            <a-input :disabled="disabled" class="formInput" v-model="userData.phone" @input="inputPhone" @blur="inPhones"></a-input>
          </div>
        </div>
        <div class="layout-right-top">
          <div class="layout-center-top">
            <a-upload
              name="avatar"
              lisType="picture"
              :showUploadList="false"
              :action="userData.userImg"
              :disabled="disabled"
              @change="uplodPic"
              accept="image/jpg,image/jpeg,image/png"
            >
              <a-avatar shape="square" icon="user" :size="100" :src="userData.userImg" :disabled="disabled"/>

            </a-upload>
            <div class="layout-side margin-bottom-10-px" style="margin-top: 26px;">
              <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>身份证号</div>
              <a-input :disabled="disabled" class="formInput" v-model="userData.idCard" @input="inputIdcard" @blur="inCardMessage"></a-input>
            </div>
            <div class="layout-side margin-bottom-10-px">
              <div class="formSpan">性别</div>
              <a-select :disabled="disabledGender" placeholder="" class="formInput" v-model="userData.gender">
                <a-select-option value="999">请选择</a-select-option>
                <a-select-option value="0">男</a-select-option>
                <a-select-option value="1">女</a-select-option>
              </a-select>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
  import {Table,Tabs, Tag, Divider, Icon, Button, Input, Modal,Popconfirm,Avatar,Select,Upload,TreeSelect,message} from 'ant-design-vue'
  import {pic2Base64} from '../../lib/utils'
  import {indexConfig} from './IndexConfig'
  import {pagination} from "../../lib/utils";

  export default {
    name: "Army",
    components: {
      ATreeSelect:TreeSelect,
      ATable: Table,
      AModal:Modal,
      ATag: Tag,
      ADivider: Divider,
      AIcon: Icon,
      AButton: Button,
      AButtonGroup: Button.Group,
      AInput:Input,
      APopconfirm:Popconfirm,
      AAvatar:Avatar,
      ASelect:Select,
      ASelectOption:Select.Option,
      AUpload:Upload,
      ATabs:Tabs,
      ATabPane:Tabs.TabPane,
    },
    data() {
      return {
        remarkStar:'1',
        orPass:true,
        selectCodes:'',
        selectDatas:[],
        routerIDs:null,
        clickIds:undefined,
        values:"请选择",
        armyTypesDatas:[],
        addB:false,
        footers:this.slot,
        disabled:false,
        disabledGender:true,
        isMessCount:1,
        userDataTable:[],
        columns:indexConfig.columns,
        armyTypeData:indexConfig.armyTypeData,
        userTypeData:indexConfig.userTypeData,
        userData:{
          name:'',
          armyType:'999',
          code:'',
          gender:'0',
          idCard:'',
          password:'123456',
          phone:'',
          userImg:'',
          remark:'1',
          userType:'999',
          userParentId:'',
        },
        rowSelection:null,
        selectRowUser:[],
        loading:false,
        modalPersonnel: false,
        userModalTitle:'新增人员',
        updateSomeUsers:false,
        contentHeight:100,
        paginationUser:pagination(this.changePage,this.showSizeChange),
      }
    },
    watch:{
      monitorClientHeight:function (old,now) {
        console.log(old,now)
        now===0?this.contentHeight = old -400:this.contentHeight = old - 400;
      },
      $route(to,from){
        this.routerIDs = to.query.id;
        if(to.query.id===undefined){
          this.routerIDs='999';
        }
        if(to.query.id === undefined||to.query.id ==='999'){
          this.showTable();
        }else {
          this.showTableIDs();
        }
      },
      orPass(val, oldVal) {
        if(this.routerIDs==='999'){
          this.showTable();
        }else {
          this.showTableIDs();
        }
      }
    },
    computed:{
      monitorClientHeight(){
        return this.$store.getters.contentHeight;
      }
    },
    mounted() {
      this.routerIDs = this.$route.query.id;
      console.log(this.$store.getters.contentHeight)
      if(this.$store.getters.contentHeight !== 0){
        this.contentHeight = this.$store.getters.contentHeight - 400;
      }
      this.routerIDs = this.$route.query.id;
      if(this.$route.query.id === "999"||this.$route.query.id === undefined){
        this.showTable();
      }else {
        this.showTableIDs();
      }
      this.onData();
    },
    methods: {
      //离开联系方式
      inPhones(){
        if(this.userData.phone.length!==7 && this.userData.phone.length!==11){
          this.$message.error('电话号码位数不对，请重新输入');
          this.userData.phone ='';
        }
      },
      //限制手机号
      inputPhone(e){
        this.userData.phone = e.target.value.replace(/[^\d]/g,'');
      },
      //限制身份证号
      inputIdcard(e){
        this.userData.idCard = e.target.value.replace(/[^a-zA-Z\d]/g,'');
      },
      //身份证号验证性别
      inCardMessage(){
        let reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
        if(reg.test(this.userData.idCard) === true){
          if(parseInt(this.userData.idCard.substr(16,1))%2 === 0){
            this.userData.gender ="1";
          }else {
            this.userData.gender ="0";
          }
        }else {
          this.$message.error('身份证格式不对，请重新输入');
          this.userData.idCard='';
        }
      },
      callback(key) {
        if(key ==="1"){
          this.orPass = true;
          this.remarkStar = "1";
        }else {
          this.orPass =false;
          this.remarkStar = "0";
        }
      },
      //审核
      onPassM(e){
        console.log(e)
        const that = this;

        this.$apollo.query({
          query:require('../../graphql/army/query/findUserById.gql'),
          variables:{id:e},
          fetchPolicy:'no-cache'
        }).then((data)=>{
          const findUserById = data.data.findUserById;
          delete findUserById.__typename;
          findUserById.remark = '1';
          const upData=[];
          that.$apollo.mutate({
            mutation:require('../../graphql/army/mutation/saveUser.gql'),
            variables:{entity:findUserById},
          }).then((data)=>{
            console.log(data)
            that.showTableIDs();
            that.$message.success('审核成功！');
          }).catch(error => {
            console.log(error);
          })
        }).catch(error => {
          console.log(error);
        })
      },
      //搜索
      selectCode(){
        const that = this;
        that.userDataTable =[]
        if(that.selectCodes === ""){
          that.$message.error("请输入查询编号！");
        }else {
          for(let i in that.selectDatas){
            if(that.selectCodes === that.selectDatas[i].code){
              that.userDataTable.push(that.selectDatas[i]);
            }
          }
        }
      },
      //清空
      removeBack(){
        const that = this;
        that.userDataTable = that.selectDatas
      },
      //表格关联树加载
      showTableIDs(){
        const that = this;
        that.userDataTable = [];
        if(that.routerIDs===undefined){
          that.routerIDs = '999';
        }
        that.$apollo.query({
          query: require('../../graphql/army/query/findAllByUserParentIdAndRemark.gql'),
          variables: {id:that.routerIDs,remark:that.remarkStar},
          fetchPolicy: 'no-cache'
        }).then(data => {
          const findAllUser = data.data.findAllByUserParentIdAndRemark;
          for(let i in findAllUser){
            let msg='';
            let mag = '';
            for(let j in that.userTypeData){
              if(findAllUser[i].userType === that.userTypeData[j].key){
                msg = that.userTypeData[j].title;
              }
            }
            for(let k in that.armyTypeData){
              if(findAllUser[i].armyType === that.armyTypeData[k].key){
                mag = that.armyTypeData[k].title;
              }
            }
            const some=[];
            some.push(msg,mag);
            that.userDataTable.push({
              key: findAllUser[i].id,
              code: findAllUser[i].code,
              name: findAllUser[i].name,
              faceBase64: findAllUser[i].userImg,
              Types: some,
            })
          }
          that.selectDatas = that.userDataTable;
        }).catch(error => {
          console.log(error);
        })
      },
      //表格加载
      showTable(){
        const that = this;
        that.userDataTable = [];
        that.$apollo.query({
          query: require('../../graphql/army/query/findAllUserByRemark.gql'),
          variables: {remark:that.remarkStar},
          fetchPolicy: 'no-cache'
        }).then(data => {
          const findAllUser = data.data.findAllUserByRemark;
          for(let i in findAllUser){
            let msg='';
            let mag = '';
            for(let j in that.userTypeData){
              if(findAllUser[i].userType === that.userTypeData[j].key){
                msg = that.userTypeData[j].title;
              }
            }
            for(let k in that.armyTypeData){
              if(findAllUser[i].armyType === that.armyTypeData[k].key){
                mag = that.armyTypeData[k].title;
              }
            }
            const some=[];
            some.push(msg,mag);
            that.userDataTable.push({
              key: findAllUser[i].id,
              code: findAllUser[i].code,
              name: findAllUser[i].name,
              faceBase64: findAllUser[i].userImg,
              Types: some,
            })
          }
          that.selectDatas = that.userDataTable;
        }).catch(error => {
          console.log(error);
        })

      },
      //展示数据字典中树的递归函数(弹出框设备类型)
      dataTreeDgData(pt, tree) {
        const that = this;
        let newRR = [];
        for (let t of tree) {
          if (pt.id === t.armyParentId) {
            let ct = that.dataTreeDgData(t, tree);
            if (ct.length !== 0) {
              newRR.push({
                title: t.armyName,
                children: ct,
                key: t.id,
                value: t.id,
                type: 'fatherNode',
              });
            } else {
              newRR.push({
                title: t.armyName,
                key: t.id,
                value: t.id,
                type: 'childNode',
              });
            }
          }
        }
        return newRR;
      },
      //新增 父级树选择
      onData() {
        const that = this;
        that.$apollo.query({
          query: require('../../graphql/army/query/findAllArmy.gql'),
          variables: {},
          fetchPolicy: 'no-cache'
        }).then(data => {
          const equipmentTree = data.data.findAllArmy;
          const newTree = [];
          for (let r of equipmentTree) {
            if (r.armyParentId === '999') {
              let ct = that.dataTreeDgData(r, equipmentTree);
              if (ct.length !== 0) {
                newTree.push({
                  title: r.armyName,
                  key: r.id,
                  value: r.id,
                  children: that.dataTreeDgData(r, equipmentTree),
                  type: 'fatherNode',
                })
              } else {
                newTree.push({
                  title: r.armyName,
                  key: r.id,
                  value: r.id,
                  type: 'childNode',
                })
              }
            }
          }
          that.armyTypesDatas = [{
            title: '建制总览',
            key: '999',
            value:'999',
            children: newTree
          }];
        }).catch(error => {
          console.log(error);
        })
      },
      //编制上级
      onSelect(value,node,extra){
        this.values=node.title;
        this.userData.userParentId = value;
      },
      //图头像
      uplodPic(e){
        const that=this;
        let files = e.file.originFileObj;
        let size = e.file.size;
        if(size < 1024*1024){
          pic2Base64(files).then(function (result) {
            that.userData.userImg = result;
          });
        }else {
          if(that.isMessCount === 1){
            that.isMessError = that.$message.error('图片大小不能大于1M')
          }
          if(that.isMessCount === 3){
            that.isMessCount = 0;
          }
        }
        that.isMessCount++;

      },
      //选择每页多少条后回调
      showSizeChange(current,pageSize){
        this.changePage(current,pageSize)
      },
      //点击页码回调
      changePage(current,pageSize){
        const that = this;
        that.paginationUser.defaultPageSize = pageSize;
        that.paginationUser.current = current;
      },
      //新增
      addUser(){
        this.addB = true;
        this.onData();
        this.userModalTitle = '人员新增';
        this.modalPersonnel = true;
        if(this.routerIDs !==null){
          this.values = this.routerIDs;
          this.userData.userParentId = this.routerIDs
        }else {
          this.values = "请选择";
          this.userData.userParentId = "";
        }
      },
      //批量删除按钮
      deleteSomeUser(){
        this.updateSomeUsers = true;
        this.rowSelection = {
          selectRowUser:this.selectRowUser,
          onChange:this.onSelectChange
        }
      },
      //人员表选择
      onSelectChange(selectedRowKeys){
        this.selectRowUser = selectedRowKeys;
      },
      deleteSomeUserCancle(){
        this.updateSomeUsers = false;
        this.selectRowUser.length = 0;
        this.rowSelection = null;
      },
      deleteSomeUserOK(){
        let row = [];
        if(this.selectRowUser.length<1){
          this.$message.error('未选择人员，请重新选择！');
          return;
        }
        for(let i in this.selectRowUser){
          row.push(this.selectRowUser[i])
        }
        this.$apollo.mutate({
          mutation:require('../../graphql/army/mutation/deleteUsers.gql'),
          variables:{ids:row}
        }).then((data)=>{
          this.showTable();
          this.$message.success("删除成功！");
        }).catch((error)=>{
          console.log(error)
        })
      },
      //人员弹框右上角X按钮
      cancelPersonnel(e) {
        this.modalPersonnel = false;
        setTimeout(()=>{
          this.handleReset();
        },200)
      },
      //人员新增确认
      addPersonnel() {
        const that = this;
        if(that.userData.name === ""){
          that.$message.error('未填写账户名！');
          return;
        }
        if(that.userData.code === ""){
          that.$message.error('未填写编号！');
          return;
        }
        if(that.userData.userParentId === ""){
          that.$message.error('未选择上级建制！');
          return;
        }
        if(that.userData.armyType === ""||that.userData.armyType === "999"){
          that.$message.error('未选择用户类别！');
          return;
        }
        if(that.userData.userType === ""||that.userData.userType === "999"){
          that.$message.error('未选择身份类别！');
          return;
        }
        if(that.userData.idCard === ""){
          that.$message.error('未输入身份证号！');
          return;
        }
        that.userData.gender = parseInt(that.userData.gender);
        that.$apollo.mutate({
          mutation:require('../../graphql/army/mutation/saveUser.gql'),
          variables:{entity:that.userData},
        }).then((data)=>{
          if(data.data.saveUser.code === "CODE_204"){
            that.$message.error("该编号已存在，请重新填写！");
          }else {
            that.$message.success("新增成功！");
            that.showTable();
            that.handleReset();
            that.modalPersonnel = false;
          }
          that.loading = true;
          setTimeout(() => {
            that.loading = false;
          }, 200);
        }).catch(error=>{
          console.log(error);
        })

      },
      //人员修改确认
      updatePersonnel() {
        const that=this;
        if(that.userData.name === ""){
          that.$message.error('未填写账户名！');
          return;
        }
        if(that.userData.code === ""){
          that.$message.error('未填写编号！');
          return;
        }
        if(that.userData.userParentId === ""){
          that.$message.error('未选择上级建制！');
          return;
        }
        if(that.userData.armyType === ""||that.userData.armyType === "999"){
          that.$message.error('未选择用户类别！');
          return;
        }
        if(that.userData.userType === ""||that.userData.userType === "999"){
          that.$message.error('未选择身份类别！');
          return;
        }
        if(that.userData.idCard === ""){
          that.$message.error('未输入身份证号！');
          return;
        }
        const upData = [];
        upData.push({
          id:that.clickIds,
          name:that.userData.name,
          armyType:that.userData.armyType,
          code:that.userData.code,
          gender:parseInt(that.userData.gender),
          idCard:that.userData.idCard,
          password:that.userData.password,
          phone:that.userData.phone,
          userImg:that.userData.userImg,
          remark:that.userData.remark,
          userType:that.userData.userType,
          userParentId:that.userData.userParentId,
        })
        that.$apollo.mutate({
          mutation:require('../../graphql/army/mutation/saveUser.gql'),
          variables:{entity:upData[0]},
        }).then((data)=>{
          console.log(data)
          if(data.data.saveUser.code === "CODE_204"){
            that.$message.error("该编号已存在，请重新填写！");
          }else {
            that.$message.success("修改成功！");
            that.showTable();
            that.handleReset();
            that.modalPersonnel = false;
          }
          that.loading = true;
          setTimeout(() => {
            that.loading = false;
          }, 200);
        }).catch(error=>{
          console.log(error);
        })
      },
      //人员弹框重置按钮
      handleReset() {
        this.disabled = false;
        setTimeout(()=>{
          this.footers = this.slot;
        },200)
        this.userData={
          name:'',
          armyType:'999',
          code:'',
          gender:'0',
          idCard:'',
          password:'',
          phone:'',
          userImg:'',
          remark:'1',
          userType:'999',
          userParentId:'',
        }
      },
      onViewClick(id) {
        const that = this;
        that.footers = null;
        that.disabled = true;
        this.userModalTitle = '人员详情';
        // this.$emit('onView', id)
        this.$apollo.query({
          query:require('../../graphql/army/query/findUserById.gql'),
          variables:{id:id},
          fetchPolicy:'no-cache'
        }).then((data)=>{
          const findUserById = data.data.findUserById;
          that.userData={
            name:findUserById.name,
            armyType:findUserById.armyType,
            code:findUserById.code,
            gender:findUserById.gender.toString(),
            idCard:findUserById.idCard,
            password:findUserById.password,
            phone:findUserById.phone,
            userImg:findUserById.userImg,
            remark:findUserById.remark,
            userType:findUserById.userType,
            userParentId:findUserById.userParentId,
          };
          that.values = findUserById.userParentId;
          that.modalPersonnel = true;
        }).catch((error)=>{
          console.log(error)
        })
      },
      onEditClick(id) {
        const that = this;
        that.clickIds = id;
        that.addB = false;
        that.userModalTitle = '人员编辑';
        that.$apollo.query({
          query:require('../../graphql/army/query/findUserById.gql'),
          variables:{id:id},
          fetchPolicy:'no-cache'
        }).then((data)=>{
            const findUserById = data.data.findUserById;
          that.userData={
            name:findUserById.name,
            armyType:findUserById.armyType,
            code:findUserById.code,
            gender:findUserById.gender.toString(),
            idCard:findUserById.idCard,
            password:findUserById.password,
            phone:findUserById.phone,
            userImg:findUserById.userImg,
            remark:findUserById.remark,
            userType:findUserById.userType,
            userParentId:findUserById.userParentId,
            };
          that.values = findUserById.userParentId;
          that.modalPersonnel = true;
        }).catch((error)=>{
          console.log(error)
        })
      },
      onDeleteClick(id) {
        const that=this;
        console.log(id)
        // this.userModalTitle = '查看详情';
        // this.modalPersonnel = true;
        const ids = []
        ids.push(id)
        this.$apollo.mutate({
          mutation:require('../../graphql/army/mutation/deleteUsers.gql'),
          variables:{ids:ids}
        }).then((data)=>{
          that.showTable();
          that.$message.success("删除成功！");
        }).catch((error)=>{
          that.$message.error("删除失败！");
          console.log(error)
        })
        // this.$emit('onDelete', id)
      },
    }
  }
</script>

<style scoped>

</style>
